<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class CommentController extends Controller
{
    //评价页面
    public function getIndex(Request $request)
    {
    	// session('redirect') = $request->Url();
    	// dd(session('redirect'));

    	return view('home.comment.comment',['request'=>$request]);
    }

    //提交评论
    public function postDocomment(Request $request)
    {
    	$data = $request->except('_token','path','order_id');
    	// dd($request->order_id);
        //时间
        $data['time'] = time();
        //用户
        $data['user_id'] = session('id');
        //初始评论 pid为0
        $data['pid'] = 0;
        $data['status'] = 1;
        $data['order_id'] = $request->input('order_id');
        // dd($data);
        // dd($data);
        //开启事务
        DB::beginTransaction();
        //插入评论表
        $cid = DB::table('shop_comments')->insertGetId($data);
        // dd($cid);
    	// 处理图像 插入评论图片表
        if(!empty($cid)){
        	// 处理图像
	        if($request->hasfile('path')){
	            $d = [];
	            // 获取所有的文件对象
	            $files=$request->file('path');
	            foreach ($files as $k => $v) {
	                $fileName = time().rand(100000,999999);
	                $suffix = $v->getClientOriginalExtension();
	                $fileName = $fileName.'.'.$suffix;
	                $dir = './Uploads/comments/'.date('Ymd').'/';
	                $v->move($dir,$fileName);
	                // 拼接OK的图片路径(绝对路径)
	                $tmp['path'] = trim($dir.$fileName,'.');
	                $tmp['comments_id'] = $cid;
	                $d[] = $tmp;
	            }
	    	}
	    	$res = DB::table('shop_compics')->insert($d);
	    	
	    	//确认事务
	    	DB::commit();
	    	return redirect('/home/order')->with('info','评论成功');
        }else{
        	//回滚
        	DB::rollBack();
        	return back()->with('error','评论失败');
        }


        
    }
}
